import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { FileUpload } from 'primeng/components/fileupload/fileupload';
import { Message, ConfirmationService, SelectItem } from 'primeng/api';
import { Propertylist } from '../../interface';
import { CountryUtilsService } from '../../../shared/services/country-utils.service';
import { ProjectService } from '../../service/project.service';
import { Router } from '@angular/router';
import { AbmComponent } from 'angular-baidu-maps';
import * as coordtransform from 'coordtransform';
import { AttachmentUtilsService } from '../../../shared/services/attachment-utils.service';
import { MessageUtilsService } from '../../../shared/services/message-utils.service';
import { SettingsService } from '../../service/settings';
import * as _ from 'lodash';
declare const BMap: any;
// var coordtransform=require('coordtransform');
@Component({
  selector: 'app-project-detail-edit',
  templateUrl: './project-detail-edit.component.html',
  styleUrls: ['./project-detail-edit.component.scss']
})
export class ProjectDetailEditComponent implements OnInit {

  project:any = {};
  googleMapUrl: any;
  @Input() id;
  propertyStatus: boolean = true;
  propertyFeatured: boolean = false;
  logos: Array<FileUpload | void> = [];
  multiPic: Array<FileUpload | void> = [];
  listbrochure: Array<FileUpload | void> = [];
  msgs: Message[] =  []
  options:any={};
  cdropDownOptions = this.countryUtilsService.dropDownOptions;
  cdropDownSelected = this.countryUtilsService.dropDownSelected;
  mapGoogleType: boolean = true;

  featureOptions:SelectItem[] = [];
  typeOptions:SelectItem[] = [];


  constructor(
    private confirmationService: ConfirmationService,
    private messageUtilsService: MessageUtilsService,
    private attachmentUtilsService:AttachmentUtilsService,
    private projectService: ProjectService,
    private countryUtilsService: CountryUtilsService,
    private settingsService:SettingsService,
    private router: Router
  ) {  }

  ngOnInit() {
    
   

    this.typeOptions = [
      {label:'HOUSE', value:'HOUSE'},
      {label:'TOWNHOUSE', value:'TOWNHOUSE'},
      {label:'APARTMENT', value:'APARTMENT'},
      {label:'LAND', value:'LAND'},
      {label:'RURAL', value:'RURAL'}
    ]

    this.settingsService.getAll().subscribe(
      (res)=>{
        this.featureOptions = [];
        _.each(res, (item)=>{
          console.log({label: item.name, value:item.id});
          this.featureOptions.push({label: item.name, value:item.id});
        });
        this.initProject();
      }
    );
  }



  //ui-event

  onStatusSwitchChange(e) {
    this.project['status'] = e.checked ? 'active' : 'inactive';
  }

  onFeaturedSwitchChange(e) {
    this.project['isFeatured'] = e.checked;
  }


  onUpdateProject() {
    this.updatePropertylist();
  }


  onRreshDropDownOptions(event){
    this.countryUtilsService.refreshDropDownOptions();
    console.log(this.cdropDownSelected);
  }

  onBaiduMap(map: any){
      let x = this.project['x'];
      let y = this.project['y'];

      //wgs84转国测局坐标
      var wgs84togcj02=coordtransform.wgs84togcj02(x, y);
     //国测局坐标转百度经纬度坐标
      var gcj02tobd09=coordtransform.gcj02tobd09(wgs84togcj02[0],wgs84togcj02[1]);
      console.log(gcj02tobd09);
      //baidu 121.326079,31.247389
      //google 31.2384481,121.3182744
      let point = new BMap.Point(gcj02tobd09[1], gcj02tobd09[0]);
      map.centerAndZoom(point, 15);
      var marker = new BMap.Marker(point);        // 创建标注    
      map.addOverlay(marker);                     // 将标注添加到地图中
      map.addControl(new BMap.MapTypeControl());
      // map.setCurrentCity('北京');
      map.enableScrollWheelZoom(true);
      // alert('s');
    
  }



  initProject() {
    if (this.id === 0) {
      this.project = {};
      this.countryUtilsService.constructDropDownOptions();
    } else {
      this.loadListDetail(this.id);
    }
  }


  loadListDetail(id) {
    this.projectService.getProjectDetail(id)
      .subscribe({
        next: (res: Propertylist): void => {
          this.project = res;
          this.enrichResponse();
        },
      });
  }


  updatePropertylist() {
    this.enrichRequest();
    this.projectService.upsertPorpertyListDetail(this.project).subscribe(
      (res) => {
        this.id = res.data.id;
        this.initProject();
        // console.log(res);
        this.messageUtilsService.showInfo(this.msgs,"success");
        history.back();
        // this.router.navigate(['/admin/shared/project-grid']);
      },
      (err)=>{
        console.log(err);
        this.messageUtilsService.showError(this.msgs,"Operation Failed.");
      }
    )
  }

  deletePropertylist() {
    this.projectService.deletePropertyListDetail(this.project['id'])
      .subscribe({
        next: (res: Propertylist): void => {
          console.log('delete success');
        },
      });
  }

  fileUpload(belongToCategory, fileUploader, entity, deleteOrigin=false) {
    if(this.id === 0){
      this.messageUtilsService.showError(this.msgs,"Please save project first before upload files");
      return;
    }
    
    let attachment = {
      entity: entity,
      belongToID: entity.id,
      belongToCategory: belongToCategory,
      files: fileUploader.files
    };
    this.attachmentUtilsService.uploadFile(attachment, deleteOrigin).subscribe(
      (res) => {
        this.messageUtilsService.showInfo(this.msgs," Attahement update success");
        fileUploader.clear();
        entity[belongToCategory] = res.data;
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs,"Operation Failed.");
      }
    );
  }

  deleteFile(attachment) {
    this.projectService.deleteAttachment(attachment).subscribe(
      (res) => {
        this.messageUtilsService.showInfo(this.msgs,attachment.originalFilename + " delete success");
        this.project[attachment.belongToCategory] = res['data'];
        // this.initPropertyList();
      },
      (err) => {
        console.log(err);
        this.messageUtilsService.showError(this.msgs,"Operation Failed.");
      }
    );
  }

  //parse response
  enrichResponse(){
    this.projectService.escapeAll(this.project, false);
    this.propertyStatus = this.project['status'] === 'active' ? true : false;
    this.propertyFeatured = this.project['isFeatured'];
    this.project.settlementDate = this.project.settlementDate ? new Date(this.project.settlementDate) : null;
    this.project.featureIds = this.project.iFeatures ? this.project.iFeatures.map(feature => {
      return feature.id;
    }) : [];
    this.countryUtilsService.constructDropDownOptions(this.project['country'],this.project['state'],this.project['city']);
    
  }

  //enrich entity before post
  enrichRequest() {
    this.project['status'] = this.propertyStatus ? 'active' : 'inactive';
    this.project['isFeatured'] = this.propertyFeatured;
    this.projectService.escapeAll(this.project, true);
    this.project['country'] = this.countryUtilsService.getSelectedCountry();
    this.project['state'] = this.countryUtilsService.getSelectedState();
    this.project['city'] = this.countryUtilsService.getSelectedCity();
  }



}
